package com.uduemc.biso.master.backend.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.github.pagehelper.PageInfo;
import com.uduemc.biso.core.common.extities.CMasterUserData;
import com.uduemc.biso.core.extities.center.MasterUser;
import com.uduemc.biso.core.utils.JsonResult;
import com.uduemc.biso.master.backend.components.LoginForm;
import com.uduemc.biso.master.backend.request.MastermanageAppend;
import com.uduemc.biso.master.backend.service.MastermanageService;

/**
 * 主控端控制台管理
 * 
 * @author guanyi
 *
 */
@Controller
@RequestMapping("/backend/mastermanage")
public class BMastermanageController {

	@Autowired
	private MastermanageService mastermanageServiceImpl;

	@Autowired
	private PasswordEncoder passwordEncoder;

	/**
	 * 创建主控端后台登录用户
	 * 
	 * @param modelAndView
	 * @return
	 * @throws IOException
	 * @throws JsonProcessingException
	 * @throws JsonMappingException
	 * @throws JsonParseException
	 */
	@GetMapping(value = { "/userappend" })
	public ModelAndView userappend(ModelAndView modelAndView)
			throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		modelAndView.setViewName("backend/mastermanage/userappend");
		return modelAndView;
	}

	/**
	 * 通过 ajax 请求添加主控制台用户数据信息
	 * 
	 * @param mastermanageAppend
	 * @param error
	 * @return
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws JsonProcessingException
	 * @throws IOException
	 */
	@PostMapping(value = { "/userappend/ajax" })
	@ResponseBody
	public JsonResult userappendAjax(@Valid @RequestBody MastermanageAppend mastermanageAppend, BindingResult error)
			throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		if (error.hasErrors()) {
			for (FieldError fieldError : error.getFieldErrors()) {
				String defaultMessage = fieldError.getDefaultMessage();
				return JsonResult.messageWarning(defaultMessage);
			}
		}
		MasterUser userAppend = mastermanageServiceImpl.userAppend(mastermanageAppend);
		if (userAppend == null) {
			return JsonResult.assistance();
		}
		return JsonResult.messageSuccess("添加成功！", userAppend);
	}

	/**
	 * 主控制台用户列表
	 * 
	 * @param modelAndView
	 * @return
	 * @throws IOException
	 * @throws JsonProcessingException
	 * @throws JsonMappingException
	 * @throws JsonParseException
	 */
	@GetMapping(value = { "/userlist" })
	public ModelAndView userlist(ModelAndView modelAndView)
			throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		modelAndView.setViewName("backend/mastermanage/userlist");
		return modelAndView;
	}

	/**
	 * 主控制台用户列表 ajax 请求
	 * 
	 * @param modelAndView
	 * @return
	 * @throws IOException
	 * @throws JsonProcessingException
	 * @throws JsonMappingException
	 * @throws JsonParseException
	 */
	@GetMapping(value = { "/userlist/ajax" })
	@ResponseBody
	public JsonResult userlistAjax(@RequestParam(value = "username", defaultValue = "") String username,
			@RequestParam(value = "status", defaultValue = "-1") short status,
			@RequestParam(value = "loginNode", defaultValue = "-1") short loginNode,
			@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
			@RequestParam(value = "orderByString", defaultValue = "1") String orderByString)
			throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		if (StringUtils.hasText(orderByString)) {
			if (orderByString.equals("1")) {
				orderByString = "`master_user`.`id` ASC";
			} else if (orderByString.equals("2")) {
				orderByString = "`master_user`.`id` DESC";
			} else {
				orderByString = "";
			}
		}
		PageInfo<CMasterUserData> userInfos = mastermanageServiceImpl.userInfos(username, status, loginNode, pageNumber,
				orderByString);
		return JsonResult.ok(userInfos);
	}

	/**
	 * 通过参数更新 master_user 数据
	 * 
	 * @param id
	 * @param status
	 * @return
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws JsonProcessingException
	 * @throws IOException
	 */
	@PostMapping(value = { "/userlist/update-one-status" })
	@ResponseBody
	public JsonResult userlistUpdateOneStatus(@RequestParam("id") long id, @RequestParam("loginNode") short loginNode,
			@RequestParam("status") short status)
			throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		MasterUser masterUser = mastermanageServiceImpl.getById(id);
		if (masterUser == null) {
			return JsonResult.illegal();
		}
		if (masterUser.getLoginNode() != null && masterUser.getLoginNode().shortValue() == loginNode
				&& masterUser.getStatus() != null && masterUser.getStatus().shortValue() == status) {
			return JsonResult.messageSuccess("更新成功！", masterUser);
		}

		masterUser.setLoginNode(loginNode).setStatus(status);
		MasterUser updateById = mastermanageServiceImpl.updateById(masterUser);
		if (updateById == null) {
			return JsonResult.assistance();
		}
		return JsonResult.messageSuccess("更新成功！", updateById);
	}

	@PostMapping(value = { "/userlist/resetpassword" })
	@ResponseBody
	public JsonResult userlistResetpassword(@RequestParam("id") long id)
			throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		MasterUser masterUser = mastermanageServiceImpl.getById(id);
		if (masterUser == null) {
			return JsonResult.illegal();
		}
		boolean matches = passwordEncoder.matches("Ab123456", masterUser.getPasswordHash());
		if (matches) {
			return JsonResult.messageSuccess("重置密码成功！", masterUser);
		}
		String encode = passwordEncoder.encode("Ab123456");
		masterUser.setPasswordHash(encode);
		MasterUser updateById = mastermanageServiceImpl.updateById(masterUser);
		if (updateById == null) {
			return JsonResult.assistance();
		}
		return JsonResult.messageSuccess("重置密码成功！", updateById);
	}

	@PostMapping(value = { "/userlist/update-user-password" })
	@ResponseBody
	public JsonResult updateUserPassword(@RequestParam("oldPassword") String oldPassword,
			@RequestParam("newPassword") String newPassword, HttpServletRequest request)
			throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		HttpSession session = request.getSession();
		LoginForm loginForm = (LoginForm) session.getAttribute("loginForm");
		if (loginForm == null || loginForm.getMasterUser() == null) {
			return JsonResult.illegal();
		}
		Long id = loginForm.getMasterUser().getId();
		MasterUser masterUser = mastermanageServiceImpl.getById(id);
		if (masterUser == null) {
			return JsonResult.illegal();
		}
		boolean matches = passwordEncoder.matches(oldPassword, masterUser.getPasswordHash());
		if (!matches) {
			return JsonResult.messageError("旧密码不正确！");
		}
		masterUser.setPasswordHash(passwordEncoder.encode(newPassword));
		MasterUser updateById = mastermanageServiceImpl.updateById(masterUser);
		if (updateById == null) {
			return JsonResult.assistance();
		}
		return JsonResult.messageSuccess("修改密码成功！", updateById);
	}

}
